package com.global.dao.impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Repository;

import com.global.dao.SystemParameterDao;
import com.global.model.SystemParameter;
import com.global.vo.LabelValue;

@Repository("systemParameterDao")
public class SystemParameterDaoImpl extends GenericDaoHibernate<SystemParameter, Long>  implements SystemParameterDao {

	public SystemParameterDaoImpl() {
		super(SystemParameter.class);
	}

	/**
	 * {@inheritDoc}
	 */
	public SystemParameter saveSystemParameter(SystemParameter para) {
		if(para!=null){
	        if (log.isDebugEnabled()) {
	            log.debug("systemParameter's id: " + para.getId());
	        }
	        getHibernateTemplate().saveOrUpdate(para);
	        getHibernateTemplate().flush();
		}
		
		return para;
	}
	
	/**
	 * {@inheritDoc}
	 */
	public boolean saveBatchSystemParameter(List<SystemParameter> paraList) {
		if(paraList!=null){
			getHibernateTemplate().saveOrUpdateAll(paraList);
			getHibernateTemplate().flush();
			
			return true;
		}

		return false;
	}
	
	/**
	 * {@inheritDoc}
	 */
	public List<SystemParameter> getSystemParameterList() {
		return this.getAll();
	}
	
	/**
	 * {@inheritDoc}
	 */
	public SystemParameter getSystemParameter(String uniqueName) {
		if(StringUtils.isNotBlank(uniqueName)){
			HashMap<String, Object> queryParams = new HashMap<String, Object>();
	        queryParams.put("uniqueName", uniqueName);
			List<SystemParameter> list = this.findByNamedQuery("findSystemParameterByName", queryParams);
			if(!list.isEmpty()){
				return list.get(0);
			}
		}

		return null;
	}

	/**
	 * {@inheritDoc}
	 */
	@SuppressWarnings("unchecked")
	public List<LabelValue> getParameterValue(List<String> uniqueNameList) {
		ArrayList<LabelValue> result = new ArrayList<LabelValue>();
		
		if(uniqueNameList!=null && !uniqueNameList.isEmpty()){
			StringBuilder sql = new StringBuilder();
			sql.append("select name, value from SystemParameter s where upper(s.name) in (");
			if(uniqueNameList.size()>1){
				for(int i=0; i<uniqueNameList.size()-1; i++){
					sql.append(uniqueNameList.get(0).toUpperCase() + ",");
				}
			}
			sql.append(uniqueNameList.get(uniqueNameList.size()-1));

			sql.append(")");			
			
			List<Object[]> list = getHibernateTemplate().find(sql.toString());
			for(Object[] o : list){
				LabelValue labelValue = new LabelValue((String)o[0], (String)o[1]);
				result.add(labelValue);
			}
		}
		
		return result;
	}
	
	/**
	 * {@inheritDoc}
	 */
	public String getParameterValue(String uniqueName) {
		List<String> uniqueNameList = new ArrayList<String>(1);
		uniqueNameList.add(uniqueName);
		List<LabelValue> list = getParameterValue(uniqueNameList);
		return list.isEmpty() ? "" : list.get(0).getValue();
	}
}
